package com.itany.action;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author 陈华旺
 * @version 1.0
 * @date 2023年11月24日 9:32
 * @Description TODO
 */
@WebServlet("/code")
public class CodeAction extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String word = "01234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";

//        完成从种子中加载随机值
        Random r = new Random();
        int len = word.length();
        StringBuffer code = new StringBuffer();
//        验证码的生成会延迟到 图形绘制
//        for (int i = 0; i < 4; i++) {
//            int j = r.nextInt(len);
//            code.append( word.charAt(j) );
//        }

//        基于随机值生成验证码图片
//        1. 构建图片
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//        + 获取图形对象 - 获取笔触
        Graphics gs = image.getGraphics();
//        + 设置笔触颜色
        gs.setColor( Color.LIGHT_GRAY );
//        gs.setColor( new Color(255,255,255) );
//        + 图片的背景填充
        gs.fillRect(0,0,width,height);

//        + 设置文字类型
        gs.setFont( new Font("宋体",Font.BOLD+Font.ITALIC,24) );
//        2. 设置在图片上书写文字的字体类型
        for (int i = 0; i < 4; i++) {
            int j = r.nextInt(len);
            char c = word.charAt(j);
            code.append( c ); // 记录验证码
            gs.setColor( new Color( r.nextInt(255),r.nextInt(255),r.nextInt(255) ) );
            gs.drawString( String.valueOf(c), 5 + (i*18),20);
        }

        req.getSession().setAttribute("code",code.toString());

        ServletOutputStream outputStream = resp.getOutputStream();
        ImageIO.write(image,"PNG",outputStream);
    }
}








